/**
 *
 * Copyright 2010 TeleNav, Inc. All rights reserved.
 * AndroidPersistentContext.java
 *
 */
package com.telenav.persistent;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;


public class PersistentContext
{
    private static PersistentContext instance = new PersistentContext();
    
    private Context context;
    private SQLiteDatabase sqliteDatabase;
    
    public static PersistentContext getInstance()
    {
        return instance;
    }
    
    public void init(Context context)
    {
        this.context = context;
    }
    
    public void closeSQLiteDatabase()
    {
        if(sqliteDatabase == null)
            return;
        
        try
        {
            if(sqliteDatabase != null)
            {
                sqliteDatabase.close();
            }
        }
        catch(Exception e)
        {
        	e.printStackTrace();
        }
        finally
        {
            try
            {
                SQLiteDatabase.releaseMemory();
            }
            catch(Exception e)
            {
            	e.printStackTrace();
            }
            
            sqliteDatabase = null;
        }
    }

    public SQLiteDatabase getApplicationSQLiteDatabase()
    {
        return sqliteDatabase;
    }

    public void openSQLiteDatabase()
    {
        if(sqliteDatabase == null || !sqliteDatabase.isOpen())
        {
            try
            {
                if(sqliteDatabase != null)
                {
                    sqliteDatabase.close();
                }
            }
            catch(Exception e)
            {
            	e.printStackTrace();
            }
            
            sqliteDatabase = this.context.openOrCreateDatabase(getApplicationName() + ".db", Context.MODE_PRIVATE, null);
        }
    }

    public Context getContext()
    {
        return this.context;
    }

    public String getApplicationName()
    {
        return "Activities_" + context.getPackageName();
    }

}
